package com.datang.yourtomcat01;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
/*
 * @auther 顶风少年
 * @mail dfsn19970313@foxmail.com
 * @date 2019-09-16 16:06
 * @notify 相应内容
 * @version 1.0
 */
public class Response {
    private static final int BUFFER_SIZE = 1024;
    Request request;
    OutputStream output;

    public Response(OutputStream output) {
        this.output = output;
    }

    /*
     * @author 顶风少年
     * @date 2019/9/16 17:01
     * @mail dfsn199703132038@foxmail.com
     * @throws
     * @param
     * @param request
     * @result void
     * @notify 设置request
     * version 1.0
     */
    public void setRequest(Request request) {
        this.request = request;
    }

    /*
     * @author 顶风少年
     * @date 2019/9/16 17:02
     * @mail dfsn199703132038@foxmail.com
     * @throws
     * @param
     * @result void
     * @notify 相应资源
     * version 1.0
     */
    public void sendStaticResource() throws IOException {
        //存放资源字节
        byte[] bytes = new byte[BUFFER_SIZE];
        //输入流
        FileInputStream fis = null;
        try {
            //尝试创建请求资源文件
            File file = new File(HttpServer.WEB_ROOT, request.getUri());

            //如果请求资源存在
            if (file.exists()) {
                fis = new FileInputStream(file);
                //将文件内容读取到字节数组中
                int ch = fis.read(bytes, 0, BUFFER_SIZE);
                //如果读取到了内容
                while (ch != -1) {
                    //将内容写入到响应体
                    output.write(bytes, 0, ch);
                    //再次读取
                    ch = fis.read(bytes, 0, BUFFER_SIZE);
                }
            } else {
                //每一找到请求资源
                String errorMessage = "HTTP/1.1 404 File Not Found\r\n" +
                        "Content-Type:text/html\r\n" +
                        "Content-Length: 23\r\n" +
                        "\r\n" +
                        "<h1>File Not Found</h1>";
                //写入提示信息
                output.write(errorMessage.getBytes());
            }
        } catch (Exception e) {
           e.printStackTrace();
        } finally {
            //关闭流
            if (fis != null) {
                fis.close();
            }
        }
    }
}
